
#-----------------------------------------------------
# Check and email logs
#-----------------------------------------------------
Import-Module SQLPS -DisableNameChecking

#current server name
$servername = "ROGUE"

$server = New-Object "Microsoft.SqlServer.Management.Smo.Server" $servername

#get the last 10 error entries, and convert to HTML
$content = ($server.ReadErrorLog() |
Where {$_.Text -like "*failed*" -or $_.Text -like "*error*" -or $_.HasErrors -eq $true} |
Select LogDate, ProcessInfo, Text, HasErrors  -Last 10   | 
ConvertTo-Html)

#email settings
$currdate = Get-Date -Format "yyyy-MM-dd hmmtt"
$smtp = "mail.rogue.local"
$to = "DBA <administrator@rogue.local>"
$from = "DBMail <dbmail@administrator.local>"
$subject = "Last 10 Errors as of $currdate"

#send the email
Send-MailMessage -SmtpServer $smtp -To $to -from $from  -Subject $subject -Body "$($content)" -BodyAsHtml




#-----------------------------------------------------
# Monitor Failed Jobs
#-----------------------------------------------------
Import-Module SQLPS -DisableNameChecking

#current server name
$servername = "ROGUE"
$server = New-Object "Microsoft.SqlServer.Management.Smo.Server" $servername

#get a list of jobs that failed, and convert to HTML
$content = ($server.JobServer.Jobs | 
Where LastRunOutcome -eq "Failed" | 
Select Name, LastRunDate | 
ConvertTo-Html)

#email settings 
$currdate = Get-Date -Format "yyyy-MM-dd hmmtt"
$smtp = "mail.rogue.local"
$to = "DBA <administrator@rogue.local>"
$from = "DBMail <dbmail@administrator.local>"
$subject = "Failed Jobs as of $currdate"

Send-MailMessage -SmtpServer $smtp -To $to -from $from  -Subject $subject -Body "$($content)" -BodyAsHtml



#-----------------------------------------------------
# Alert Disk Space
#-----------------------------------------------------
#current server name
$servername = "ROGUE"
#if free space % falls below this threshold, 
#assign CSS class critical which makes font red  
$criticalthreshold = 10

#inline css for styling
$inlinecss = @"
<style>
   table
   {
      margin: 0px;
      border: 1px solid #7e7e7e;
      background-color: #fafafa;
      border-collapse: collapse;
   }

   tr:nth-child(even) /* doesnt work in IE8 */
   {
       background-color: #d5e4f4;
   }

   th, td
   {
       width: 100px;
       text-align: left;
   }

   th
   {
       background-color:#a6bdd6;
       font-weight:bold;
   }

   .critical, .critical td
   {
      color: red;
      font-weight: bold;
   }
</style>
"@

#construct the html content
#use single quotes so we can use double quotes inside
$htmlhead = "<head><title>Disk Space Report </title>$($inlinecss)</head>"
$htmlbody = "<body>"
$htmlbody += "<p>$($subject)</p>"
$htmlbody += "<table><tbody>"
$htmlbody += "<th>Device ID</th>"
$htmlbody += "<th>Size (GB)</th>"
$htmlbody += "<th>Free Space (GB)</th>"
$htmlbody += "<th>Free Space (%)</th>"

#get disk usage 
#to look only at Local Disk, add filter for DriveType -eq 3
Get-WmiObject -Class Win32_LogicalDisk -ComputerName $servername |
ForEach-Object {
   $disk = $_
   $size = "{0:N1}" -f ($disk.Size/1GB)
   $freespace = "{0:N1}" -f ($disk.FreeSpace/1GB)
   if ($disk.Size -gt 0)
   {
      $freespacepercent = "{0:P0}" -f ($disk.FreeSpace/$disk.Size)
   }
   else 
   {
      $freespacepercent = ""
   }
   if ($freespacepercent -ne "" -and $freespacepercent -le $criticalthreshold)
   {
      $htmlbody += "<tr class='critical'>"
   }
   else
   {
      $htmlbody += "<tr>"
   }
   $htmlbody += "<td>$($disk.DeviceID)</td>"
   $htmlbody += "<td>$($size)</td>"
   $htmlbody += "<td>$($freespace)</td>"
   $htmlbody += "<td>$($freespacepercent)</td>"
   $htmlbody += "</tr>"
}
$htmlbody += "</tbody></table></body></html>"
$htmlcontent = $htmlhead + $htmlbody

#email settings
$currdate = Get-Date -Format "yyyy-MM-dd hmmtt"
$smtp = "mail.rogue.local"
$to = "DBA <administrator@rogue.local>"
$from = "DBMail <dbmail@administrator.local>"
$subject = "Disk Space Report for $servername as of $currdate"

Send-MailMessage -SmtpServer $smtp -To $to -from $from  -Subject $subject -Body "$($htmlcontent)" -BodyAsHtml



#-----------------------------------------------------
# Log blocking processes
#-----------------------------------------------------
Import-Module SQLPS -DisableNameChecking

$logname = "Application"
$source = "SQL Server Custom"

#current server name
$servername = "ROGUE"

$server = New-Object "Microsoft.SqlServer.Management.Smo.Server" $servername

$blockedprocesses = $server.EnumProcesses() |
Where IsSystem -eq $false |
Where BlockingSpid -gt 0 |
Select Spid, Database, BlockingSpid, 
Login, Status 

#check if Event Log source exists, otherwise create
if(!([System.Diagnostics.EventLog]::SourceExists($source)))
{
   Write-Output "Creating a new source"
   New-EventLog -LogName $logname -Source $source
}

#compose message
$message = "Blocked Process Identified `r`n`r`n" + $blockedprocesses

#write to event log with custom source
Write-EventLog -LogName $logname -Source $source -EventId 1  -EntryType Warning -Message $message




#-----------------------------------------------------
# Get performance metrics
#-----------------------------------------------------
#current server name
$servername = "ROGUE"

Get-Counter -ComputerName $servername -ListSet * | 
Sort-Object CounterSetName | 
Select CounterSetName |
Format-Table



#-----------------------------------------------------
# Create Data Collector Set
#-----------------------------------------------------
#current server name
$servername = "ROGUE"

#data collector set name
$dcsname = "SQL Performance Metrics"

$dcs = New-Object -COM Pla.DataCollectorSet
$dcs.DisplayName = $dcsname

#subdirectory format will have year and month
#enum value is plaYearMonth, which is 0x0800
$dcs.SubdirectoryFormat = 0x0800 

#specify path where data collector set will be stored
#typically this will be in the system drive
$dcs.RootPath = "%systemdrive%\PerfLogs\Admin\" + $dcsname 

#now need to set up each file
$datacollector = $dcs.DataCollectors.CreateDataCollector(0)

#file format is binary
#enum is plaBinary = 3
$datacollector.LogFileFormat = 3

$datacollector.FileName = $dcsname + "_"

#filename format will have year, month and day
#enum value is plaYearMonthDay 0x1000
$datacollector.FileNameFormat = 0x1000 
$datacollector.SampleInterval = 15
$datacollector.LogAppend = $true

#these are the counters we want to capture
#you can add more to this, or can pull this from a file
$counters = @(
    "\Memory\Available MBytes", 
    "\Network Interface(*)\Bytes Received/sec",
    "\Network Interface(*)\Bytes Sent/sec",
    "\PhysicalDisk\Avg. Disk Sec/Read",
    "\PhysicalDisk\Avg. Disk Sec/Write",
    "\PhysicalDisk\Avg. Disk Queue Length",
    "\Processor(_Total)\% Processor Time"
) 

#add the counters to the data collector
$datacollector.PerformanceCounters = $counters
$dcs.DataCollectors.Add($datacollector) 
    
#save datacollectorset 
#name, server, commit mode, createnewormodify
$dcs.Commit("$dcsname" , $servername , 0x0003) 
